package com.blueocean_health.care.management.util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import com.blueocean_health.care.management.domain.dto.NurseWorkerInfoHealthCertResponseDto;

/**
* 护工模块短工具类
* @author huyanqiu
* @date 2017年12月20日 上午11:50:48
* @version 版本号：1.0
*/
public class NurseMessageUtils {
	
	// 用户名
	private final static String username = "lanhaihy";
	// 密码
	private final static String password = "okmlya";
	
	// 正常短信模板
	private static String template1 = "【蓝海健康】尊敬的护理员workerName先生/女士：您的健康证（编号HealthCert）将于ExpiryDate失效，为避免无法顺利派工，请于失效前及时办理新的健康证，感谢配合！";
	// 已过期短信模板
	private static String template2 = "【蓝海健康】尊敬的护理员workerName先生/女士：您的健康证（编号HealthCert）已于ExpiryDate失效，目前已失去上工资格，请及时办理新的健康证，并到项目部进行登记，感谢配合！";
	// 失效日期为空短信模板
	private static String template3 = "【蓝海健康】尊敬的护理员workerName先生/女士：您还没有办理健康证，为避免无法顺利派工，请及时办理健康证并到项目部进行登记，感谢配合！";
	
	static class Code {
//		 // 失败
//		private final static String ERROR = "-1";
		// 成功
		private final static String SUCCESS = "1";
//		// 产品错误（联系客服）
//		private final static String PRODUCTWRONG = "11";   	/////
//		// 产品禁用（联系客服） 
//		private final static String PRODUCTDISABLE = "12";  /////
//		// 手机号码错误
//		private final static String MOBILEWRONG = "13";
//		// 签名不合规
//		private final static String FORMATERROR = "15";
//		// 签名屏蔽
//		private final static String SIGNATUREDISABLE = "16";
//		// 代表签名分配扩展失败,20160xxxxx代表消息编号（21位消息ID）
//		private final static String XXXX = "17";           /////
//		// 短信内容不能为空
//		private final static String CONTENTNOTNULL = "18";
//		// 短信内容最大500个字
//		private final static String MAX500 = "19";
//		// 预付费用户条数不足
//		private final static String NOSUM = "20";
//		// 通道错误（联系客服）
//		private final static String CHANNLERROR = "22"; /////
//		// 签名最长30个字
//		private final static String SIGNATRUEMAX15 = "22";
//		// 小号错误
//		private final static String XHWRONG = "29"; /////
//		// 异常（联系客服）
//		private final static String EXCEPTION = "22";  /////
//		// DES解密Exception
//		private final static String DESXCEPTION = "22"; /////
		
	}
	
	public static void main(String[] args) throws IOException {
	}
	
	/**
	 * 单条短信发送
	 * @param bean 短信内容
	 * @throws java.lang.Exception 
	 * @throws IOException 
	 */
	public static void sendSingleMessage(NurseWorkerInfoHealthCertResponseDto bean) throws java.lang.Exception {
		// 单条短信接口地址
		String url = "http://api.zthysms.com/sendSms.do";
		String tkey = getFormatedDateString();
		String passwordMd5 = AES.GetMD5(AES.GetMD5(password)+tkey);
		String content = "";
		// 获取短信发送类型  type 1:正常短信 2、已过期短信  3、失效日期为空
		int type = messageType(bean);
		if (type==1) {
			content = template1.replaceAll("workerName", bean.getWorkerName()).replaceAll("HealthCert", bean.getHealthCert()).replaceAll("ExpiryDate", date2String(bean.getHealthCertExpiryDate()));
		} else if (type==2) {
			content = template2.replaceAll("workerName", bean.getWorkerName()).replaceAll("HealthCert", bean.getHealthCert()).replaceAll("ExpiryDate", date2String(bean.getHealthCertExpiryDate()));
		} else if (type==3) {
			content = template3.replaceAll("workerName", bean.getWorkerName());
		}
		Connection conn = Jsoup.connect(url).ignoreContentType(true);
		conn.data("username", username);
		conn.data("tkey", tkey);
		conn.data("password", passwordMd5);
		conn.data("mobile", bean.getPhone());
		conn.data("content", content);
		conn.data("xh", "");
		conn.post(); 
		String body = conn.response().body();
		String str = body.split(",")[0];  //  1,201712201408283311964
		if (!Code.SUCCESS.equals(str)) {
			throw new java.lang.Exception("短信发送失败，失败原因："+body);
		}
	}
	
	/**
	 * 批量发送短信服务
	 * @param list
	 * @throws java.lang.Exception 
	 * @throws Exception 
	 */
	public static void sendBatchMessage(List<NurseWorkerInfoHealthCertResponseDto> list) throws java.lang.Exception{
		StringBuffer mobile = new StringBuffer();
		StringBuffer content = new StringBuffer();
		for (NurseWorkerInfoHealthCertResponseDto bean : list) {
			// 获取短信发送类型
			int type = messageType(bean);
			if (type==1) {
				content.append(template1.replaceAll("workerName", bean.getWorkerName()).replaceAll("HealthCert", bean.getHealthCert()).replaceAll("ExpiryDate", date2String(bean.getHealthCertExpiryDate()))+"※");
			} else if (type==2) {
				content.append(template2.replaceAll("workerName", bean.getWorkerName()).replaceAll("HealthCert", bean.getHealthCert()).replaceAll("ExpiryDate", date2String(bean.getHealthCertExpiryDate()))+"※");
			} else if (type==3) {
				content.append(template3.replaceAll("workerName", bean.getWorkerName())+"※");
			}
			// 手机号码
			mobile.append(bean.getPhone()+",");
		}
		String url = "http://api.zthysms.com/sendSmsBatchIdentity.do";
		String tkey = getFormatedDateString(); // ※
		String passwordMd5 = AES.GetMD5(AES.GetMD5(password)+tkey);
		Connection conn = Jsoup.connect(url).ignoreContentType(true);
		conn.data("username", username);
		conn.data("tkey", tkey);
		conn.data("password", passwordMd5);
		conn.data("mobile", mobile.deleteCharAt(mobile.length()-1).toString());
		conn.data("content", content.deleteCharAt(content.length()-1).toString());
		conn.data("xh", "");
		conn.post(); 
		String body = conn.response().body();
		String str = body.split(",")[0];  //  1,201712201408283311964
		if (!Code.SUCCESS.equals(str)) {
			throw new java.lang.Exception("短信发送失败，失败原因："+body);
		}
	}
	
	/**
	 * Date类型转化成yyyy年MM月dd日
	 * @param date
	 * @return
	 */
	private static String date2String(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
		return format.format(date);
	}
	
	/**
     * 获得东八区时间   yyyyMMddHHmmss
     * @param timeZoneOffset
     * @return
     */
    public static String getFormatedDateString(){
        int newTime=(int)(8 * 60 * 60 * 1000);
        TimeZone timeZone;
        String[] ids = TimeZone.getAvailableIDs(newTime);
        timeZone = new SimpleTimeZone(newTime, ids[0]);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        sdf.setTimeZone(timeZone);
        return sdf.format(new Date());
    }
    
    /**
	 * 获得发送短信模板类型
	 * @param bean
	 * @throws IOException 
	 */
	private static int messageType(NurseWorkerInfoHealthCertResponseDto bean){
		// 健康证有效期为空
		if ("".equals(bean.getDays())) {
			return 3;
		}
		// 已过期
		else if ("已过期".equals(bean.getDays())) {
			return 2;
		} 
		// 即将失效
		else if ("即将失效".equals(bean.getDays())) {
			return 1;
		}
		// 正常情况
		else {
			return 1;
		}
	}
	
}
